﻿using Microsoft.EntityFrameworkCore;
using Naruto.Repository;
using Naruto.TaskManagement.Entitys;
using Naruto.TaskManagement.Entitys.Models;
using Naruto.TaskManagement.Entitys.VM;
using Naruto.TaskManagement.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Naruto.TaskManagement.Repository
{
    /// <summary>
    /// 聊天记录的数据仓储
    /// </summary>
    public class ChatMessageRepository : IChatMessageRepository
    {
        private readonly IRepository<TaskManagementContext> repository;

        public ChatMessageRepository(IRepository<TaskManagementContext> _repository)
        {
            repository = _repository;
        }
        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task Add(ChatMessage info)
        {
            await repository.Command<ChatMessage>().AddAsync(info);
        }

        /// <summary>
        /// 更改所有未读消息状态 为已读
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task UpdateRead(string id)
        {
            await repository.Command<ChatMessage>().UpdateAsync(a => a.Id == id, entity =>
            {
                entity.IsRead = true;
                return entity;
            });
        }

        /// <summary>
        /// 获取我的消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="reciveUserId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<List<GetMyChatMessageViewModel>> GetMyChatMessage(string userId, string reciveUserId, int pageIndex, int pageSize)
        {
            var chatMessageQuerable = await repository.QueryAsync<ChatMessage>();
            return await chatMessageQuerable.Where(a => (a.SendUserId == userId && a.RecevieUserId == reciveUserId) || (a.RecevieUserId == userId && a.SendUserId == reciveUserId)).Select<ChatMessage, GetMyChatMessageViewModel>().OrderByDescending(a => a.CreateTime).PageBy(pageIndex, pageSize).AsNoTracking().ToListAsync();
        }
    }
}
